package com.sbtr.controller.classify;

import com.sbtr.business.classify.dto.AlgoTemplateDto;
import com.sbtr.business.classify.entity.AlgoParamVersion;
import com.sbtr.business.classify.entity.AlgoTemplate;
import com.sbtr.business.classify.service.AlgoParamVersionService;
import com.sbtr.business.classify.service.AlgoTemplateParamService;
import com.sbtr.business.classify.service.AlgoTemplateService;
import com.sbtr.business.feature.dto.FeDatafileUploadDto;
import com.sbtr.business.feature.entity.FeDatafield;
import com.sbtr.common.LoginConstants;
import com.sbtr.common.PageDto;
import com.sbtr.common.Response;
import com.sbtr.controller.MaterialInfoController;
import com.sbtr.controller.common.CommonController;
import com.sbtr.exception.BDException;
import com.sbtr.util.DateHelper;
import com.sbtr.util.FileHelper;
import com.sbtr.util.HttpServletRequestUtil;
import com.sbtr.util.StringHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.omg.CORBA.StringHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 轻量化算法模板(高质量芯片项目) 前端控制器
 *
 * @author maojianping
 * @since 2023-04-17
 */
@RestController
@RequestMapping("/algoTemplate")
@ApiIgnore
public class AlgoTemplateController extends CommonController<AlgoTemplate,AlgoTemplateService> {

    private Logger logger = LoggerFactory.getLogger(AlgoTemplateController.class);

    @Autowired
    AlgoTemplateParamService algoTemplateParamService;

    @Autowired
    AlgoParamVersionService algoParamVersionService;

    @GetMapping("/pageList")
    @ApiOperation(httpMethod = "GET", value = "分页列表")
    public Response<PageDto<AlgoTemplate>> pageList(AlgoTemplateDto algoTemplateDto){
        return Response.success(u.pageList(algoTemplateDto));
    }

    @PostMapping("/save")
    @ApiOperation(httpMethod = "POST", value = "新增算法模板基本信息")
    public Response<AlgoTemplate> save(@RequestBody AlgoTemplate algoTemplate){
        algoTemplate.setId(null);
        System.err.println("userName:"+HttpServletRequestUtil.getLoginUserName());
        if (algoTemplate.insert()) {
            return Response.success(algoTemplate);
        } else throw new BDException("新增算法模板基本信息失败");
    }

    @PostMapping("/uploadTemplateAndExtractor")
    @ApiOperation(httpMethod = "POST", value = "上传算法模板文件并提取默认版本参数")
    public Response<AlgoTemplate> uploadTemplateAndExtractor(AlgoTemplateDto algoTemplateDto,
           @RequestPart(value = "file", required = false) MultipartFile file, HttpServletRequest request){

        String username = request.getParameter(LoginConstants.REQUEST_PARAM_USERNAME);
        try{
            AlgoTemplate algoTemplate = u.uploadAndExtractor(algoTemplateDto,file,username);
            if(StringHelper.isNotEmpty(algoTemplate.getBucketDir())){
                return Response.success(algoTemplate);
            }else throw new BDException("上传算法模板文件提取出现异常");
        }catch (Exception e){
            logger.error(e.getMessage());
            throw new BDException("上传失败："+e.getMessage());
        }
    }

    @ApiOperation(httpMethod = "POST", value = "根据算法模板版本号ID完成轻量化算法模板一键生成")
    @RequestMapping(value = "/generationAlgoTemplate")
    @ResponseBody
    public void generationAlgoTemplate(@RequestParam(value = "algoVersionId") Long algoVersionId,
                                       HttpServletResponse response){
        String error = "";
        File file = null;
        try {
            AlgoTemplateDto algoDto = u.generationAlgoTemplate(algoVersionId); // 返回临时构造后的算法模板dto对象
            if(StringHelper.isNotEmpty(algoDto.getPackageurl())){
                file = new File(algoDto.getPackageurl());
                FileHelper.downLoadFileBroswer(algoDto.getFilename(), response, file); // 下载
            }else{
                error = "【"+algoDto.getAlgoname()+"】算法模板生成失败！";
                response.setHeader("errormsg", URLEncoder.encode(error, "UTF-8"));
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }finally {
            file.delete(); // 删除已经输出的压缩包文件，并关闭所有流
        }
    }

    /**
     * 删除算法记录，并关联删除算法文件、算法参数历史版本等信息
     * @param ids
     * @return
     */
    @PostMapping("/deleteByIds")
    @ApiOperation(httpMethod = "POST", value = "根据id批量删除（同时删除本算法关联的算法文件、历史算法参数版本、算法版本关联参数集等信息）,逗号分隔ps:'1,2,3'")
    public Response<String> deleteByIds(String ids){

        List<String> listStr = Arrays.asList(ids.split(","));
        List<Long> listIds = StringHelper.convertStrToNumber(listStr, Long.class);
        // 遍历删除算法信息、关联算法文件、关联算法版本、算法版本关联参数集
        if(!u.batchDelete(listIds)){
            throw new BDException("批量删除失败");
        }
        return Response.success("批量删除成功");
    }

    @ApiOperation(value = "根据id删除", notes = "根据id删除（同时删除本算法关联的算法文件、历史算法参数版本、算法版本关联参数集等信息）", httpMethod = "DELETE")
    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.DELETE)
    public Response<Boolean> deleteById(@PathVariable("id") Long id) {

        // 遍历删除算法信息、关联算法文件、关联算法版本、算法版本关联参数集
        boolean b = u.delete(id);
        if (!b)
            throw new BDException("删除失败");

        return Response.success("删除成功", b);
    }

}

